/**
 * 业户综合分析考核
 */
$(function(){
	EnterpriseAnaQC.init();
});

var EnterpriseAnaQC = {
	GlobalGpsCache:[],
	init: function(){
		var me = this;
		me.initQueryTime();
		me.initEvent();
		//me.loadTableTitle();
		me.queryTable();
		me.initEntList();
		
	},
	initEvent: function(){
		var me = this;
		$('#timeSelect').on('change',function(){
			me.pickTime();
		});
		$("#queryBtn").click(function(){
			me.queryTable();
    	});
		$("#exportQcExcel").click(function(){
			me.exportQcExcel();
		});
	},
	/**
	选择时间的输入框被选中时，创建datepicker控件
	根据设置不同dateFmt 格式，使空间支持选择日，周，月，季，年
	*/
	 createWdatePicker:function() {
	    var type = $("#timeSelect").val();
	    var me = this;
	    if (type == 1) {
	    	//按日
	        WdatePicker({
	            readOnly : true,
	            dateFmt : 'yyyy-MM-dd',
	           // onpicked : me.pickTime,
	            isShowWeek : false,
	            maxDate : '%y-%M-{%d-1}'
	        });
	    } else if (type == 2) {
	    	//按周
	    } else if (type == 3) {
	    	//按月
	        WdatePicker({
	            readOnly : true,
	            dateFmt : 'yyyy-MM',
	            //onpicked : me.pickTime,
	            isShowWeek : true,
	            maxDate : '%y-%M'
	        });
	    } else if (type == 4) {
	    	//按季
	        WdatePicker({
	            readOnly : true,
	            dateFmt : 'yyyy年MM季度',
	            isQuarter:true, 
	            isShowOK:false, 
	            disabledDates:['....-0[5-9]-..','....-1[0-2]-..'], 
	            //startDate:'{%y-1}-01-01' 
	            onpicked : function(){
	            	$('.navImg NavImgl').attr("style='display: none;'");
	            },
	            //isShowWeek : true,
	            maxDate : '%y-{%M/3-1}-%d'
	        });
	    } else if (type == 5) {
	    	//按年
	        WdatePicker({
	            readOnly : true,
	            dateFmt : 'yyyy年',
	           // onpicked : me.pickTime,
	            isShowWeek : true,
	            maxDate : '%y'
	        });
	    }

	},
	pickTime : function(){
	    var type = $("#timeSelect").val();
	    var todayDate = new Date();
        var todayDateStr=todayDate.getFullYear()+"-"+(todayDate.getMonth()+1)+"-"+todayDate.getDate();  
        var beforeDate = new Date(todayDate-86400000*1); //前一天
	    var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString();
	    if (mm.length == 1) {
	        mm = '0' + mm;
	    }
	    if (type == 1) {//按日
	    	$("#selectWeek").hide();
	    	$("#selectDate").show();
	    	if (dd.length == 1) {
		        dd = '0' + dd;
		    }
	        $("#inputDate").val(yyyy + '-' + mm + '-' + dd);
	    } else if (type == 2) {//按周
	    	$("#selectDate").hide();
	    	$("#selectWeek").show();
	    	$.ajax({
	    		type : 'post',
	    		url : appCtx + "base/report/PlatformAnalyzes/queryweek.html",
	    		cache : false,
	    		dataType : "JSON",
	    		success : function(data) {
	    			if(data!=null&&data!=''){
	    				$.each(data,function(entryIndex,entry) {
	    					$("#week").append("<option value='"+entry.value+"'>"+entry.text+"</option>");
	    				});	
	    			}
	    		}
	    	});
	    } else if (type == 3) {//按月
	    	$("#selectWeek").hide();
	    	$("#selectDate").show();
	    	var month = parseInt(mm) ;
	    	if (dd<24) {
	    		month = month-1;
			}
	    	if (month < 10) {
	    		month = '0' + month;
		    }
	    	$("#inputDate").val(yyyy + '-' + month);
	    } else if (type == 4) {//按季
	        //计算季度的开始月份和结束月份
	    	$("#selectWeek").hide();
	    	$("#selectDate").show();
	        var quarter = parseInt((mm - 1) / 3) ;
	        $("#inputDate").val(yyyy + '年0' + quarter +'季度');
	    } else if (type == 5) {//按年
	    	$("#inputDate").val(yyyy + '年');
	    }
	},
    //初始化时间
    initQueryTime : function(){
    	$("#selectWeek").hide();
    	$("#selectDate").show();
        var todayDate = new Date();
        var todayDateStr=todayDate.getFullYear()+"-"+(todayDate.getMonth()+1)+"-"+todayDate.getDate();  
        var beforeDate = new Date(todayDate-86400000*1); //前一天
	    var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString();
	    if (mm.length == 1) {
	        mm = '0' + mm;
	    }
	    if (dd.length == 1) {
	        dd = '0' + dd;
	    }
        $("#inputDate").val(yyyy + '-' + mm + '-' + dd);
    },
  //处理轨迹数据
	handTrack : function(jsonData){
		var _this = this;
    	var GlobalGridField = ['index','ranking','score','enterprise_name','vehicle_access_rate','vehicle_online_rate','track_complete_rate','data_correct_rate','position_exception_rate','avg_vehicle_speed_counts','avg_vehicle_tired_duration','reply_correct_avg','adas_alarm_count'];
    	var tmpData = [],tmpValue = null;
    	for(var i = 0; i < GlobalGridField.length; i++){
    		tmpValue = jsonData[GlobalGridField[i]];

    		if(tmpValue != undefined && tmpValue != null)
    			tmpData.push(tmpValue);
    		else
    			tmpData.push("");
    	}
    	var gridData = {id:_this.GlobalGpsCache.length,data:tmpData};
    	this.GlobalGpsCache.push(gridData); 
    	//var gridData = {id:jsonData.vehicleId,data:tmpData};
    	//index.GlobalGpsCache.put(jsonData.vehicleId,gridData);
    },
	initSubDetail:function(){
		var me = this;
		var wid = iframeWidth;
		var widStr = 0.05*wid+","+0.035*wid+","+0.035*wid+","+0.17*wid+","+0.06*wid+","+0.06*wid+","
			+0.08*wid+","+0.08*wid+","+0.12*wid+","+0.07*wid+","+0.12*wid+","+(0.12*wid-22);
		var initOptions = {	// 表格配置
		           tableId:'monitorList',
		           header:'序号,排名,得分,业户名称,入网率(%),上线率(%),轨迹完整率(%),数据合格率(%),卫星定位漂移车辆率(%),平均超速次数,平均疲劳驾驶时长(分钟),平台查岗响应率(%)',
		           colTypes:'ro,ro,ro,ro,ro,ro,ro,ro,ro,ro,ro,ro',
		           code :'index,ranking,score,enterprise_name,vehicle_access_rate,vehicle_online_rate,track_complete_rate,'+
		        	   'data_correct_rate,position_exception_rate,avg_vehicle_speed_counts,avg_vehicle_tired_duration,reply_correct_avg',
		           initWidths:widStr,
		           initWidthps:widStr,
		           align:'left,left,left,left,left,left,left,left,left,left,left,left',
		           sort:'no,no,no,no,no,no,no,no,no,no,no,no'
		    	 };
		me.myGrid = new dhtmlXGridObject(initOptions.tableId);
		me.myGrid.setHeader(initOptions.header,null,["text-align:left;","text-align:left;","text-align:left;",
			"text-align:left;","text-align:left;","text-align:left;","text-align:left;","text-align:left;",
			"text-align:left;","text-align:left;","text-align:left;","text-align:left;"]);//列标题
		me.myGrid.setInitWidths(initOptions.initWidths);
		me.myGrid.setColumnIds(initOptions.code);
		me.myGrid.setColAlign(initOptions.align);//设置列数据的水平布局
		me.myGrid.setColTypes(initOptions.colTypes);//设置列数据的数据类型(ch ---- checkbox; ra ---- radio;ro ---- readonly，
				//双击具体某项数据时不可编辑的;txt ---- 显示的是字符串，双击某项数据会弹出编辑页面 )
		me.myGrid.setColSorting(initOptions.sort);
		me.myGrid.setSkin("dhx_skyblue");//指明使用什么皮肤
		me.myGrid.enableAutoHeight(false,'auto',true);
		//index.myGrid.enableAutoHeight(false);
		me.myGrid.init();
		me.myGrid.enablePreRendering(1000);
		me.myGrid.enableSmartRendering(true);
        $("#monitorList").height(iframeHeight - 10);
        $("#monitorList").width(iframeWidth);
        me.myGrid.attachEvent("onRowSelect",function(id,ind){
			//draw.drawPointMark(totalSubsection[id]);
    	 });
	},
    queryTable:function(){
    	var me = this;
    	//$("#monitorList tr:eq(1)").remove(); 
    	var enterprise_id = $.trim($("#selectEnterprise").val());
    	var inputTime = "";
    	var timeType = $("#timeSelect").val();
    	var time = $("#inputDate").val();
    	var week = $("#week").val();
    	if (timeType==1) {
			inputTime = time.substring(2,4)+time.substring(5,7)+time.substring(8,10);
		}else if(timeType==2) {
    		inputTime = week;
		}else if(timeType==3) {
			inputTime = time.substring(2,4)+time.substring(5,7);
		}else if(timeType==4) {
			inputTime = time.substring(2,4)+time.substring(5,7);
		}else if(timeType==5) {
			inputTime = time.substring(2,4);
		}
    	$.ajax({
    		url:appCtx+"base/report/enterpriseAnalyzes/queryEnterpriseQc.html",
    		type:"post",
			cache : false,
    		data:{
    			timeType:timeType,
    			inputTime:inputTime,
    			enterprise_id:enterprise_id
    		},
    		dataType:"json",
    		success:function(data){
            	me.GlobalGpsCache = [];
                if(data && data.length > 0){
                	var rowLen = data.length; 
                	for(var i=0;i<rowLen;i++){
                		var row = data[i];
                		row.index = i+1;
                		//row.vehicle_access_rate = Math.round((row.vehicle_access_rate)*Math.pow(10,2))/Math.pow(10,2);
                		//row.vehicle_online_rate = Math.round((row.vehicle_online_rate)*Math.pow(10,2))/Math.pow(10,2);
                		//row.track_complete_rate = Math.round((row.track_complete_rate)*Math.pow(10,2))/Math.pow(10,2);
                		//row.data_correct_rate = Math.round((row.data_correct_rate)*Math.pow(10,2))/Math.pow(10,2);
                		var sum = row.location_exception_count+row.speed_160_count+row.gpstime_exception_count+row.head_exception_count;
                		var rate = sum>0?row.location_exception_count/sum : 0;
                		var num = row.vehicle_online_count>0?(rate*row.exception_vehicle_count)/row.vehicle_online_count :0;
                		row.position_exception_rate=Math.round((num*100)*Math.pow(10,2))/Math.pow(10,2);
                		//row.avg_vehicle_speed_counts = row.avg_vehicle_speed_counts ? Math.round((row.avg_vehicle_speed_counts/60)*Math.pow(10,2))/Math.pow(10,2) :0;
                		row.reply_correct_avg = row.check_count>0 ? Math.round((100*row.location_exception_count/row.check_count)*Math.pow(10,2))/Math.pow(10,2) :0;
                		row.avg_vehicle_tired_duration = row.reply_correct_avg?parseInt(row.reply_correct_avg/60):0;
                		me.handTrack(row);
                	}
                	GlobalGpsCacheData = {
                			rows: me.GlobalGpsCache
                	};
                	me.myGrid.parse(GlobalGpsCacheData,"json");
                }else{
                	//$("#monitorList tr:not(:first)").remove(); 
                	//$("#monitorList tr:eq(0)").after("<tr><td colspan='10'>无数据</td></tr>"); 
                	window.parent.global.ajaxLoading.pop("查询无结果",false,1500);
                }
            }
    	});
    	me.initSubDetail();
    },
    initEntList:function(){		
    	$("#selectEnterprise").select2({
        theme: "default",
        allowClear: true,
        placeholder: "请选择业户",
        ajax:{
            url:appCtx + "base/report/enterpriseAnalyzes/queryEnterprise.html",
            dataType:"json",
            delay:250,
            data:function(params){
                return {
                	enterprise_name: params.term,
                };
            },
            cache:true,
            processResults: function (res) {
		    	if(res){
		    		var options = [];
		    		var option = {"id":" ", "text":"全部业户"};
		    		options.push(option);
    				$.each(res,function(index,obj) {
						var option = {"id":obj.id, "text":obj.enterprise_name};
	                    options.push(option);
    				});
	                return {
	                	results: options,
	                    pagination: {
	                        more:false
	                    }
	                };
		    	}
            },
            escapeMarkup: function (markup) { return markup; },
            minimumInputLength: 1
        }
    });
    },
   exportQcExcel : function(){
	   var me = this;
	   if(me.GlobalGpsCache.length==0){
		   window.parent.global.ajaxLoading.pop("无数据导出",false,2000);
		   return;
	   }
	   window.parent.global.ajaxLoading.pop("正在导出,请稍后.....", true, 2000);
		var tableDataStr="";
		for(var i=0;i<me.GlobalGpsCache.length;i++){
			var arrValue = me.GlobalGpsCache[i].data;
			tableDataStr += arrValue[0]+"#"+arrValue[1]+"#"+arrValue[2]+
			"#"+arrValue[3]+"#"+arrValue[4]+"#"+arrValue[5]+"#"+arrValue[6]+"#"+arrValue[7]+
			"#"+arrValue[8]+"#"+arrValue[9]+"#"+arrValue[10]+"#"+arrValue[11]+"#"+arrValue[12]+"&";
		}
		var tableDataTtiles="序号,排名,得分,业户名称,入网率(%),上线率(%),轨迹完整率(%),数据合格率(%),卫星定位漂移车辆率(%),平均超速次数,平均疲劳驾驶时长(分钟),平台查岗响应率(%),安全报警数";
		var param =  {
				tableDataStr:tableDataStr,
				tableDataTtiles:tableDataTtiles,
				title:"业户分析考核表",
		};
	   	post(appCtx+"base/report/enterpriseAnalyzes/QCexport.html",param);
   },
}
